package org.jeecg.modules.htxincailiao.account.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RequestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.htxincailiao.account.entity.HTForumsExpert;
import org.jeecg.modules.htxincailiao.account.entity.HTMerchant;
import org.jeecg.modules.htxincailiao.account.service.IHTForumsExpertService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.htxincailiao.forums.entity.HTForumsCategory;
import org.jeecg.modules.htxincailiao.forums.entity.HTForumsQuestion;
import org.jeecg.modules.htxincailiao.forums.service.IHTForumsCategoryService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: ht_forums_expert
 * @Author: jeecg-boot
 * @Date:   2021-12-02 09:53:38
 * @Version: V1.0
 */
@Api(tags="ht_forums_expert")
@RestController
@RequestMapping("/account/hTForumsExpert")
@Slf4j
public class HTForumsExpertController extends JeecgController<HTForumsExpert, IHTForumsExpertService> {
	@Resource
	private IHTForumsExpertService hTForumsExpertService;

	@Resource
	private IHTForumsCategoryService forumsCategoryService;

	 @Autowired
	 private ISysUserService sysUserService;

	 @Autowired
	 private BaseCommonService baseCommonService;

	 @Lazy
	 @Resource
	 private CommonAPI commonApi;

	/**
	 * 分页列表查询
	 *
	 * @param hTForumsExpert
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ht_forums_expert-分页列表查询")
	@ApiOperation(value="ht_forums_expert-分页列表查询", notes="ht_forums_expert-分页列表查询")
	@RequestMapping(value = "/list", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryPageList(HTForumsExpert hTForumsExpert,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		if (req.getMethod().equals("POST")){
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				hTForumsExpert = JSONObject.parseObject(line, HTForumsExpert.class);
				pageNo = oConvertUtils.isNotEmpty(hTForumsExpert.getPageNo()) ? hTForumsExpert.getPageNo() : pageNo;
				pageSize = oConvertUtils.isNotEmpty(hTForumsExpert.getPageSize()) ? hTForumsExpert.getPageSize() : pageSize;
			}
		}
		if(oConvertUtils.isNotEmpty(hTForumsExpert) &&
				oConvertUtils.isNotEmpty(hTForumsExpert.getExpertCategoryId()) &&
				hTForumsExpert.getExpertCategoryId().equals("0")) {
			//全部分类
			hTForumsExpert.setExpertCategoryId(null)	;
		}
		QueryWrapper<HTForumsExpert> queryWrapper = QueryGenerator.initQueryWrapper(hTForumsExpert, req.getParameterMap());
		String token = req.getHeader("X-Access-Token");
		if (StringUtils.isNotBlank(token)) {
			String username =  JwtUtil.getUsername(token);
			Set<String> roleSet = commonApi.queryUserRoles(username);
			for (String str : roleSet) {
				if(str.equals("forums-expert")){
					queryWrapper.eq("username",username);
				}
			}
		}
		queryWrapper.orderByDesc("update_time");
		Page<HTForumsExpert> page = new Page<HTForumsExpert>(pageNo, pageSize);
		IPage<HTForumsExpert> pageList = hTForumsExpertService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param hTForumsExpert
	 * @return
	 */
	@AutoLog(value = "ht_forums_expert-添加")
	@ApiOperation(value="ht_forums_expert-添加", notes="ht_forums_expert-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody HTForumsExpert hTForumsExpert) {
		Result<HTMerchant> result = new Result<HTMerchant>();
		try{
			hTForumsExpertService.save(hTForumsExpert);
			//管理员新增专家库后自动创建账号
			String selectedRoles = "1407877236295512065";
			SysUser user = new SysUser();
			user.setUsername(hTForumsExpert.getUsername());
			user.setShopId(hTForumsExpert.getId());
			user.setPhoneNumber(hTForumsExpert.getPhoneNumber());
			user.setRealname(hTForumsExpert.getRealName());
			if (org.apache.commons.lang3.StringUtils.isBlank(hTForumsExpert.getPassword())) {
				user.setPassword("123456");
			}else{
				user.setPassword(hTForumsExpert.getPassword());
			}
			String salt = oConvertUtils.randomGen(8);
			user.setSalt(salt);
			String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
			user.setPassword(passwordEncode);
			user.setStatus(1);
			user.setDelFlag(CommonConstant.DEL_FLAG_0);
			//用户表字段org_code不能在这里设置他的值
			user.setOrgCode(null);
			// 保存用户走一个service 保证事务
			sysUserService.saveUser(user, selectedRoles, null);
			baseCommonService.addLog("添加用户，username： " +user.getUsername() ,CommonConstant.LOG_TYPE_2, 2);
			result.success("添加成功！");
		}catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;

	}

	/**
	 *  编辑
	 *
	 * @param hTForumsExpert
	 * @return
	 */
	@AutoLog(value = "ht_forums_expert-编辑")
	@ApiOperation(value="ht_forums_expert-编辑", notes="ht_forums_expert-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody HTForumsExpert hTForumsExpert) {
		Result<HTMerchant> result = new Result<HTMerchant>();
		try{
			HTForumsExpert htForumsExpert = hTForumsExpertService.getById(hTForumsExpert.getId());
			String username = htForumsExpert.getUsername();//获取数据库中的用户名
			//通过用户名查找用户信息
			SysUser user = sysUserService.getUserByName(username);
			hTForumsExpertService.updateById(hTForumsExpert);
			if (user == null) {
				return result.success("编辑成功！");
			}
			//将修改的信息更新到用户账号中去
			String selectedRoles = "1407877236295512065";
			if (org.apache.commons.lang3.StringUtils.isBlank(hTForumsExpert.getPassword())) {
			}else{
				//修改了密码
				String salt = oConvertUtils.randomGen(8);
				user.setSalt(salt);
				user.setPassword(hTForumsExpert.getPassword());
				String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
				user.setPassword(passwordEncode);
			}
			user.setUsername(hTForumsExpert.getUsername());
			user.setShopId(hTForumsExpert.getId());
			user.setPhoneNumber(hTForumsExpert.getPhoneNumber());
			user.setRealname(hTForumsExpert.getRealName());
			user.setStatus(1);
			user.setDelFlag(CommonConstant.DEL_FLAG_0);
			//用户表字段org_code不能在这里设置他的值
			user.setOrgCode(null);
			// 保存用户走一个service 保证事务
			sysUserService.editUser(user, selectedRoles, null);
			baseCommonService.addLog("修改用户，username： " +user.getUsername() ,CommonConstant.LOG_TYPE_2, 2);
			result.success("编辑成功！");
		}catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_forums_expert-通过id删除")
	@ApiOperation(value="ht_forums_expert-通过id删除", notes="ht_forums_expert-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		HTForumsExpert htForumsExpert = hTForumsExpertService.getById(id);
		String username = htForumsExpert.getUsername();//获取数据库中的用户名
		//通过用户名查找用户信息
		SysUser user = sysUserService.getUserByName(username);
		if(null != user){
			//删除用户信息
			sysUserService.delUserById(user.getId());
		}
		hTForumsExpertService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ht_forums_expert-批量删除")
	@ApiOperation(value="ht_forums_expert-批量删除", notes="ht_forums_expert-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		List<String> userIdList = new ArrayList<>();
		for(String id : idList){
			HTForumsExpert htForumsExpert = hTForumsExpertService.getById(id);
			String username = htForumsExpert.getUsername();//获取数据库中的用户名
			//通过用户名查找用户信息
			SysUser user = sysUserService.getUserByName(username);
			if(null != user){
				userIdList.add(user.getId());
			}
		}
		if(userIdList.size() > 0){
			sysUserService.delUserByIds(userIdList);
		}
		this.hTForumsExpertService.removeByIds(idList);
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ht_forums_expert-通过id查询")
	@ApiOperation(value="ht_forums_expert-通过id查询", notes="ht_forums_expert-通过id查询")
	@RequestMapping(value = "/queryById", method = {RequestMethod.GET,RequestMethod.POST})
	public Result<?> queryById(HttpServletRequest req, @RequestParam(name="id",required=false) String id) {
		if (req.getMethod().equals("POST")){
			String line = RequestUtil.getPostParam(req);
			if (oConvertUtils.isNotEmpty(line)) {
				HTForumsExpert hTForumsExpert  = JSONObject.parseObject(line, HTForumsExpert.class);
				id = hTForumsExpert.getId();
			}
		}

		HTForumsExpert hTForumsExpert = hTForumsExpertService.getById(id);
		String forumsCategoryId = hTForumsExpert.getForumsCategoryId();
		String categoryName = "";
		if(forumsCategoryId.contains(",")) {
			String[] split = forumsCategoryId.split(",");
			for(int i = 0;i < split.length;i++) {
				HTForumsCategory forumsCategory = forumsCategoryService.getById(split[i]);
				categoryName = categoryName + "," + forumsCategory.getName();
			}
			categoryName = categoryName.substring(1);
			hTForumsExpert.setCategoryName(categoryName);
		} else {
			HTForumsCategory forumsCategory = forumsCategoryService.getById(forumsCategoryId);
			if (oConvertUtils.isNotEmpty(forumsCategory) && oConvertUtils.isNotEmpty(forumsCategory.getName())){
				hTForumsExpert.setCategoryName(forumsCategory.getName());
			}
		}

		if(hTForumsExpert==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hTForumsExpert);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hTForumsExpert
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTForumsExpert hTForumsExpert) {
        return super.exportXls(request, hTForumsExpert, HTForumsExpert.class, "ht_forums_expert");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTForumsExpert.class);
    }

}
